import './index.scss'
import { Divider, Table, Space, Switch, Button, Col, Form, Input, Row, Select, theme, DatePicker, Pagination, Modal, message, List } from 'antd';
import dayjs from 'dayjs'
import React, { useEffect, useState } from 'react';
import { zoneinfo } from '../../../utils/sendRequst'
import { Delete } from '../../../utils/sendRequst'
import { Inquire } from '../../../utils/sendRequst'
import { editable1 } from '../../../utils/sendRequst'
import { addition } from '../../../utils/sendRequst'
import { Link } from 'react-router-dom';



const { Option } = Select;


const Student = () => {
    // 搜索表单


    const { token } = theme.useToken();
    const [form] = Form.useForm();
    const formStyle = {
        maxWidth: 'none',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 10,
    };


    //这是专区渲染
    const [dataList, SetDataList] = useState([]);
    const [list, SetList] = useState([])

    //编辑模态框
    const [isModalOpen, setIsModalOpen] = useState(false);

    //编辑的ID
    const [dataID, setDateID] = useState([])

    //添加的模态框
    const [isModalOpen2, setIsModalOpen2] = useState(false);

    // 点击筛选后的数据及请求
    const onFinish123 = (row) => {
            Inquire(row).then(res => {
                if (res.code == 200) {
                    const list = res.data.map(item => ({ ...item, key: item.zoneId }))
                    SetDataList(list);
                    message.success("查询成功")
                } else {
                    message.success("查询失败")
    
                }
            })
        
    };

    //编辑的模态框隐藏
    const QuXiao = () => {
        setIsModalOpen(false);
    }
    //编辑的模态框确定
    const onFinishOk = (values) => {
        setIsModalOpen(false);
        let list = []
        list.push(values)
        let op = list.map((item) => ({ ...item, dataID: dataID }))
        editable1(op[0]).then(res => {
            if (res.code == 200) {
                message.success("修改成功")
                getStu();
            } else {
                message.success("修改失败")
            }
        })
    }

    //获取专区数据
    const getStu = () => {
        zoneinfo().then(res => {
            // console.log(res);
            const list = res.data.map(item => ({ ...item, key: item.zoneId }))
            SetDataList(list)


        })

    };

    //添加确定取消的模态框
    const onFinishok2 = (values) => {
        setIsModalOpen2(false);

        addition(values).then(res => {
            if (res.code == 200) {
                getStu()
                message.success("添加成功")
            } else {
                message.success("添加失败")
            }

        })
    }
    //添加取消的模态框

    //添加确定后出现的模态框
    const addTo = () => {
        setIsModalOpen2(true);
    }

    //编辑专区
    const edit = (row) => {
        const dateStr = row.zoneTimi;
        const date = new Date(dateStr);
        date.setDate(date.getDate() + 1);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate() - 1).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`; // "2023-04-10"
        row.zoneTimi = formattedDate
        SetList(row)
        setIsModalOpen(true);
        setDateID(row.zoneId)
        console.log(row);

    }


    //删除
    const shanChu = (row) => {
        console.log(list);
        if (row.zoneShelf == true) {
            message.success("当前专区已上架不可删除")
        } else {
            Delete(row).then(res => {
                if (res.code == 200) {
                    getStu();
                    message.success("删除成功")
                } else {
                    message.success("删除失败")
                }
            })
        }
    }


    const columns = [
        {
            title: '序号',
            dataIndex: 'zoneId',
        },
        {
            title: '专区名称',
            dataIndex: 'zoneName',
        },
        {
            title: '显示模板',
            dataIndex: 'zoneTemplate',
        },
        {
            title: '是否上架',
            dataIndex: 'zoneShelf',
            render: (text, record, index) => {
                return (
                    <Switch defaultChecked={record.zoneShelf}
                        disabled
                        checked={record.zoneShelf}
                    />
                );
            },

        },
        {
            title: '上架时间',
            dataIndex: 'zoneTimi',
            render: (text, record) => {
                const dateStr = record.zoneTimi;
                const date = new Date(dateStr);
                date.setDate(date.getDate() + 1);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate() - 1).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`; //               
                return (
                    <span>{formattedDate}</span>
                )
            }
        },
        {
            title: '操作',
            render: (_, record) => (
                <Space size="middle">
                     <Link to="/index/Merchandise">商品管理</Link>
                    <a onClick={() => {
                        edit(record)
                    }}>编辑</a>

                    <a onClick={() => {
                        shanChu(record)
                    }} >删除</a>
                </Space>
            ),
        },
    ];


    //获取专区数据
    useEffect(() => {
        getStu()
    }, [])

    //表格
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            name: record.name,
        }),
    };
    //改变编辑中 上下架的状态
    const onSwitchChange = (checkedValue) => {
        SetList((prevState) => ({
          ...prevState,
          zoneShelf: checkedValue
        }));
      };
      const dateFormat = 'YYYY-MM-DD';
    return (
        <div >
            <div className="heder">
                <p className="heder-text">
                    <>筛选查询</>
                </p>
                <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish123}
                    initialValues={{ name: undefined, productBrand: undefined, productGrounding: '', }}
                >
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name='name'
                                label='关键词'
                            >
                                <Input placeholder="商品名称/商品ID" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name='productBrand'//初始化动态变得数据
                                label='是否上架'
                            >
                                <Select>
                                    <Option value={0}>上架</Option>
                                    <Option value={1}>下架</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name='productGrounding'//初始化动态变得数据
                                label='上架时间'
                            >
                                <Space direction="vertical" size={12}>
                                    <DatePicker />
                                </Space>
                            </Form.Item>
                        </Col>


                    </Row>
                    <Row>
                        <Col
                            span={24}
                            style={{
                                textAlign: "center"
                            }}
                        >
                            <Button type="primary" htmlType="submit"
                            >
                                筛选
                            </Button>
                            <Button
                                style={{
                                    margin: '0 .8rem',
                                }}
                                onClick={() => {
                                    getStu();
                                    form.resetFields();
                                }}
                            >
                                重置
                            </Button>
                        </Col>
                    </Row>
                </Form>

            </div>

            <div>
                <div className="heder-text">
                    <>数据列表</>
                    <div className='hederText' onClick={addTo} >
                        <p>添加</p>
                    </div>
                </div>
                <Table pagination={{ pageSize: 5 }} rowSelection={{
                    ...rowSelection,
                }}
                    columns={columns}
                    dataSource={dataList}
                />
                <Divider />

            </div>

            {/* 编辑的模态框 */}
            <>
                <Modal title="编辑专区" open={isModalOpen} footer={null} closable={false} destroyOnClose={true}>
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinishOk}
                        autoComplete="off"
                        initialValues={{ zoneName: list.zoneName, zoneTemplate: list.zoneTemplate, zoneShelf: list.zoneShelf }}
                    >
                        <Form.Item
                            label="专区名称"
                            name="zoneName"
                            rules={[{ required: true, message: '专区名称' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="显示模板"
                            name="zoneTemplate"
                            rules={[{ required: true, message: '显示模板必选' }]}
                        >
                            <Select>
                                <Option value="单排式">单排式</Option>
                                <Option value="双排式">双排式</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="上架时间"
                            name="zoneTimi"
                            rules={[{ required: true, message: '上架时间必选' }]}
                        >
                            <DatePicker  defaultValue={dayjs(list.zoneTimi, dateFormat)} format={dateFormat}/>

                        </Form.Item>
                        <Form.Item
                            label='是否上架'
                            name="zoneShelf"
                        >
                           <Switch checked={list.zoneShelf} onChange={(checkedValue) => onSwitchChange(checkedValue)} />

                        </Form.Item>


                        <Form.Item>
                            <Button type="primary" htmlType="submit" className='btn'>
                                确定
                            </Button>
                            <Button type="default" onClick={QuXiao}>
                                取消
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </>

            {/* 添加的模态框 */}
            <>
                <Modal title="添加专区" open={isModalOpen2} footer={null} closable={false} destroyOnClose={true} >
                    <Form
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        style={{ maxWidth: 600 }}
                        onFinish={onFinishok2}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="专区名称"
                            name="zoneName"
                            rules={[{ required: true, message: '专区名称' }]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="显示模板"
                            name="zoneTemplate"
                            rules={[{ required: true, message: '显示模板必选' }]}
                        >
                            <Select>
                                <Option value="单排式">单排式</Option>
                                <Option value="双排式">双排式</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="上架时间"
                            name="zoneTimi"
                            rules={[{ required: true, message: '上架时间必选' }]}
                        >
                            <DatePicker  />

                        </Form.Item>
                        <Form.Item
                            label='是否上架'
                            name="zoneShelf"
                        >
                            <Switch value />

                        </Form.Item>


                        <Form.Item>
                            <Button type="primary" htmlType="submit" className='btn' onClick={() => {
                                form.resetFields();
                            }} >
                                确定
                            </Button>
                            <Button type="default" onClick={() => {
                                form.resetFields();
                                setIsModalOpen2(false);
                            }}>
                                取消
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        </div>
    );
}

export default Student;